﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsUpdateByZip
{
    public partial class Form1 : Form
    {
        private string URL;
        private string ProcessesName;

        public Form1()
        {
            InitializeComponent();
            this.URL = ConfigurationManager.AppSettings["url"];
            this.ProcessesName = ConfigurationManager.AppSettings["ProcessesName"];
            
        }
        public Form1(string URL,string ProcessesName)
        {
            InitializeComponent();
            this.URL = URL;
            this.ProcessesName = ProcessesName;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                //找到devhuarui的进程并关闭
                Process[] processes = Process.GetProcessesByName(ProcessesName);
                foreach (var process in processes)
                {
                    process.Kill();
                }
                this.label2.Text = URL;
                this.label3.Text = ProcessesName;
                更新();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                Application.Exit();
            }
        }

        private async void 更新()
        {
            //通过config读取配置文件的key=url
            string applicationPath = Application.StartupPath;
            string fileName = Path.GetFileName(URL);

            string filePath = Path.Combine(applicationPath, fileName);
            using (var client = new WebClient())
            {
               //client.DownloadFile(URL, filePath);
              
                Uri uri = new Uri(URL);
                //开启新线程下载文件
                client.DownloadProgressChanged += (s, e) =>
                {
                    this.progressBar1.Value = e.ProgressPercentage;
                    this.label1.Text = $"正在下载。。{e.ProgressPercentage}%";
                };
                client.DownloadFileCompleted += (s, e) =>
                {
                    this.label1.Text = "下载完成";
                    // Unzip the file
                    string extractPath = Path.Combine( applicationPath, ProcessesName);
                    //将debug解压到applicationPath
                    this.label1.Text = $"下载完成.正在解压.";
                    ExtractToDirectory(filePath, extractPath);
                    this.label1.Text = $"更新完成。请重新运行文件.";
                    this.label4.Text = $"zipPath:{filePath}";
                    this.label5.Text = $"ExtractPath:{extractPath}";
                    //删除压缩包
                    //File.Delete(filePath);
                };
                //开始异步下载
                await client.DownloadFileTaskAsync(uri, filePath);
            }
        }
        public static int ExtractToDirectory(string zipPath, string extractPath)
        {
            int fileCount = 0;
            using (var archive = System.IO.Compression.ZipFile.OpenRead(zipPath))
            {
                fileCount = archive.Entries.Count;
                foreach (var entry in archive.Entries)
                {
                    string filePath = $"{extractPath}\\{entry.FullName}";
                    if (File.Exists(filePath))
                    {
                        File.Delete(filePath);
                    }
                }
            }

            System.IO.Compression.ZipFile.ExtractToDirectory(zipPath, extractPath);
            return fileCount;
        }
    }
}
